package com.ruoyi.web.controller.tool;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.InputStream;

/**
 * @Description: OSS工具
 * @ClassName: DownloadRecDocJob
 * @Author: dujunshuai
 * @Date: 2020/02/07 11:15
 * @Version: 1.0
 */
@Component
@Slf4j
@Data
@ConfigurationProperties(prefix = "aliyun.oss")
public class OSSUtil {

    private String accessKeyId;
    private String accessKeySecret;
    private String endpoint;
    private String innerEndpoint;
    private String bucket;

    /**
     * 文件上传
     * @param fileKey OSS路径
     * @param inputStream 输入流
     * @return void
     */
    public void uploadFile(String fileKey, InputStream inputStream){
        log.info("OSS文件上传 Started");
        log.info("OSS路径: {}, ", fileKey);

        // 生成OSSClient，您可以指定一些参数，详见“SDK手册 > Java-SDK > 初始化”，
        // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/init.html?spm=5176.docoss/sdk/java-sdk/get-start
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 判断Bucket是否存在。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
            // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
            if (ossClient.doesBucketExist(bucket)) {
                log.info("您已经创建Bucket：" + bucket + "。");
            } else {
                log.info("您的Bucket不存在，创建Bucket：" + bucket + "。");
                // 创建Bucket。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
                // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
                ossClient.createBucket(bucket);
            }

            // 上传文件
            // 文件存储入OSS，Object的名称为fileKey。详细请参看“SDK手册 > Java-SDK > 上传文件”。
            // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/upload_object.html?spm=5176.docoss/user_guide/upload_object
            ossClient.putObject(bucket, fileKey, inputStream);
            log.info("Object：" + fileKey + "存入OSS成功。");
        } catch (OSSException oe) {
            oe.printStackTrace();
        } catch (ClientException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

        log.info("OSS文件上传 Completed");
    }
}
